package com.dcits.mvc.common.validator;

import java.util.regex.Pattern;

import com.dcits.constant.ConstantReturnCode;
import com.dcits.dto.RenderJSONBean;
import com.dcits.mvc.common.service.UserConfigService;
import com.dcits.tool.StringUtils;
import com.jfinal.core.Controller;
import com.jfinal.validate.ValidateException;
import com.jfinal.validate.Validator;

public class UserKeyValidator extends Validator {
	
	private static UserConfigService userConfigService = new UserConfigService();
	private String errorMsg = "参数验证不通过";
	
	public void validate(Controller controller) {
		String userKey = controller.getPara("userKey");
		String actionKey = getActionKey();
		//验证userKey
		if (actionKey.equals("/config/add")) {
			if (!StringUtils.regExpVali(Pattern.compile("^[A-Za-z0-9_]{6,10}$"), userKey)) {
				//renderError(ConstantReturnCode.VALIDATE_FAIL, "userKey不符合要求!");
				invalid = true;
				errorMsg = "userKey不符合要求:6-10位字母数字组合!";
				throw new ValidateException();
			}
			if (userConfigService.findByKey(userKey) != null) {
				//renderError(ConstantReturnCode.VALIDATE_FAIL, "userKey已存在!");
				invalid = true;
				errorMsg = "userKey已存在!";
				throw new ValidateException();
			}
		} else {
			if (userConfigService.findByKey(userKey) == null) {
				invalid = true;
				errorMsg = "userKey不正确!";
				throw new ValidateException();
			}
		}		
	}
	
	public void handleError(Controller controller) {
		RenderJSONBean json = new RenderJSONBean();
		json.setReturnCode(ConstantReturnCode.VALIDATE_FAIL);
		json.setMsg(errorMsg);
		controller.renderJson(json);
	}
}
